//! 实现修改数据功能 trait

use std::fmt::Display;

use crate::{App, AppData, FQLType};

pub trait Editor {
    fn add(&mut self, new_data: AppData);
    fn remove(&mut self, index: usize);
    fn insert(&mut self, index: usize, new_data: AppData);
    fn replace(&mut self, index: usize, new_data: AppData);
    fn update<T: Display>(&mut self, index: usize, key: T, new_value: FQLType);
}

impl Editor for App {
    /// 修改一行数据
    /// #Example
    ///```
    /// use file_sql::*;
    /// let app = App::from_file("example.fql");
    /// let new_data = app.find_index(1);
    /// app.replace(0, "age", new_data.to_owned());
    ///```
    fn replace(&mut self, index: usize, new_data: AppData) {
        self.data.remove(index);
        self.data.insert(index, new_data);
    }

    /// 在指定一行加入数据  
    fn insert(&mut self, index: usize, new_data: AppData) {
        self.data.insert(index, new_data);
    }

    /// 删除某一列数据
    /// #Example
    ///```
    /// use file_sql::*;
    /// let app = App::from_file("example.fql");
    /// app.remove(1); // 删除第二行数据
    ///```
    fn remove(&mut self, index: usize) {
        self.data.remove(index);
    }

    fn update<T: Display>(&mut self, index: usize, key: T, new_value: FQLType) {
        let mut new_data = self.data.remove(index);
        new_data.insert(key.to_string(), new_value);
        self.data.insert(index, new_data);
    }

    /// 添加数据到末尾
    fn add(&mut self, new_data: AppData) {
        self.data.push(new_data);
    }
}
